//
//  LoggerFile.swift
//  Runner
//
//  Created by Longxiang Guo (QXQ4633) on 2021/9/6.
//

import Foundation


class Logger {
    
    private static let instance = Logger()
    private var filePath: String
    private var fileHandle: FileHandle
    
    init() {
        filePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/meteric.log"
        if (!FileManager.default.fileExists(atPath: filePath)){
            FileManager.default.createFile(atPath: filePath,
                                           contents: nil,
                                           attributes: [FileAttributeKey.creationDate: Date()])
        }
        fileHandle = FileHandle(forReadingAtPath: filePath)!
        fileHandle.seekToEndOfFile()
    }
    
    static func logMessage(message: String){
        if (message.isEmpty){
            return
        }
        instance.fileHandle.write(message.data(using: String.Encoding.utf8)!)
         
        if (instance.fileHandle.availableData.count > 1024) {
            instance.fileHandle.synchronizeFile()
        }
    }
}
